import 'package:elephantgas/bean/cashier_order_record_entity.dart';
import 'package:elephantgas/common/constant.dart';
import 'package:elephantgas/network/network_manager.dart';
import 'package:elephantgas/network/network_url.dart';
import 'package:elephantgas/utils/toast_util.dart';
import 'package:elephantgas/utils/user_util.dart';
import 'package:elephantgas/widget/myappbar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class GasRecordPage extends StatefulWidget {
  @override
  _MsgState createState() => _MsgState();
}

class _MsgState extends State<GasRecordPage> {
  DateTime dateTime;
  String year, month;
  @override
  void initState() {
    super.initState();
    dateTime = DateTime.now();
    year = dateTime.year.toString();
    month = dateTime.month.toString();
    selectDate =
        dateTime.year.toString() + '年' + dateTime.month.toString() + '月';
    _getList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Color(0xFFF7F7F7),
      appBar: MyAppBar(context: context, title: '历史记录'),
      body: _content(),
    );
  }

  List<CashierOrderRecordData> mData = [];
  void _getList() {
    Map map = {
      'gasstationId': UserUtil.getUseInfo().user.authorities[0].orgId,
      'periodMonth': month,
      'periodYear': year,
    };
    DioManager.getInstance().postJson(ServiceUrl.cashier_order_record, map,
        (data) {
      _refreshController.loadComplete();
      Map queryBack = new Map<String, dynamic>.from(data);
      CashierOrderRecordEntity homeEntity =
          new CashierOrderRecordEntity().fromJson(queryBack);
      mData.clear();
      if (homeEntity.code == 0) {
        if (homeEntity.data != null && homeEntity.data.length != 0) {
          mData.addAll(homeEntity.data);
        } else {
          ToastUtil.show('暂无数据');
        }
      } else {}
      setState(() {});
    }, (error) {});
  }

  String selectDate;
  showPickerDate(BuildContext context) {
    Picker(
        hideHeader: true,
        cancelText: '取消',
        confirmText: '确认',
        adapter: DateTimePickerAdapter(
          isNumberMonth: true,
          type: PickerDateTimeType.kYM,
        ),
        title: Text("选择日期"),
        selectedTextStyle: TextStyle(color: Colors.blue),
        onConfirm: (Picker picker, List value) {
          print(value);
          String a = picker.adapter.text;
          List<String> b = a.split(' ');
          List<String> c = b[0].split('-');
          String e = c[1];
          if (e.toString().startsWith('0')) {
            e = e.substring(1, 2);
          }
          String d = c[0] + '年' + e + '月';
          selectDate = d;
          year = c[0].toString();
          month = e.toString();
          print(d);
          _getList();
        }).showDialog(context);
  }

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  Widget _month() {
    return InkWell(
        onTap: () {
          showPickerDate(context);
          // showPickerDateTime(context);
        },
        child: Container(
            margin: EdgeInsets.only(left: 13, top: 19.5),
            child: Row(
              children: [
                Text(
                  selectDate,
                  style: TextStyle(color: Color(0xFF1C1D21), fontSize: 18.sp),
                ),
                SizedBox(
                  width: 11,
                ),
                Image.asset(
                  Constant.ASSETS_IMG_CASHIER + 'arrow_down.png',
                  width: 9,
                  height: 5,
                )
              ],
            )));
  }

  Widget _buildList() {
    return Expanded(
        child: Container(
            margin: EdgeInsets.only(left: 12, right: 12, top: 23),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(2)),
            child: SmartRefresher(
              enablePullDown: false,
              enablePullUp: true,
              footer: CustomFooter(
                builder: (BuildContext context, LoadStatus mode) {
                  Widget body;
                  if (mode == LoadStatus.idle) {
                    body = Text("上拉加载更多");
                  } else if (mode == LoadStatus.loading) {
                    body = Text("加载中");
                  } else if (mode == LoadStatus.failed) {
                    body = Text("加载失败，请重试！");
                  } else if (mode == LoadStatus.canLoading) {
                    body = Text("释放加载更多");
                  } else {
                    body = Text("没有更多数据了");
                  }
                  return Container(
                    height: 50.0,
                    child: Center(child: body),
                  );
                },
              ),
              controller: _refreshController,
              onLoading: _onLoading,
              child: ListView.builder(
                shrinkWrap: true,
                itemBuilder: (c, i) {
                  return _item(i);
                },
                itemCount: mData.length,
              ),
            )));
  }

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onLoading() async {
    // monitor network fetch
    _getList();
  }

  Widget _item(index) {
    return Column(
      children: [
        Container(
          height: 49,
          margin: EdgeInsets.only(left: 12, right: 13),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Text(
                    '${mData[index].curDate}',
                    style: TextStyle(color: Color(0xFF1C1D21), fontSize: 16.sp),
                  ),
                  SizedBox(
                    width: 50,
                  ),
                  Text(
                    '${mData[index].gasQtyTotal}公斤',
                    textAlign: TextAlign.right,
                    style: TextStyle(color: Color(0xFF1C1D21), fontSize: 16.sp),
                  )
                ],
              ),
              Text(
                '${mData[index].orderTotal}单',
                style: TextStyle(color: Color(0xFF1C1D21), fontSize: 16.sp),
              )
            ],
          ),
        ),
        Container(
          height: 0.5,
          color: Color(0xFFEFEFF4),
        )
      ],
    );
  }

  Widget _content() {
    return Container(
      child: Column(
        children: [
          _month(),
          _buildList(),
        ],
      ),
    );
  }
}
